package com.funkids.prxis.controller;

import cn.hutool.core.map.MapUtil;
import com.funkids.common.Const;
import com.funkids.common.Result;
import com.funkids.config.KaptchaConfig;
import com.funkids.prxis.entity.SysUser;
import com.funkids.utils.RedisUtils;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
import java.util.UUID;

@RestController
@RequestMapping("/auth")
public class AuthController extends BaseContoller{

    @Autowired
    Producer producer;

    @Autowired
    RedisUtils redisUtils;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

//        //方便测试
//        key = "11111";
//        code = "aaaaa";

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",byteArrayOutputStream);

        Base64.Encoder encoder = Base64.getEncoder();
        String prefix = "data:image/jpeg;base64,";

        String b64image = prefix + encoder.encodeToString(byteArrayOutputStream.toByteArray());

        redisUtils.hset(Const.CAPTCHA_KEY,key,code);
        redisUtils.expire(Const.CAPTCHA_KEY,180);


        Result result = Result.succ(
                MapUtil.builder()
                        .put("token",key)
                        .put("captchaImg",b64image)
                        .build()
        );
        return result;
    }

}
